#include "Timer.h"

// Initialise all our static pointers to NULL first before we do anything
_Timer	*	_Timer::Timer_Instance	= NULL;
double	_Timer::PerformanceCounterFreq = 0;

_Timer::_Timer(void)
{
	LARGE_INTEGER temp;
	ErrorMsg(!QueryPerformanceFrequency(&temp),"Timer\t\t: Constructor - QueryPerformanceFrequency() failed");

	PerformanceCounterFreq = double(temp.QuadPart) / 1000000.0;
}

_Timer::~_Timer(void)
{
	// Delete the Instance
	if(Timer_Instance != NULL)
	{
		delete Timer_Instance;
		Timer_Instance = NULL;
	}
}

_Timer* _Timer::getInstance(void)
{
	if(Timer_Instance == NULL)
		Timer_Instance = new _Timer();

	return Timer_Instance;
}

int _Timer::GetTime(void)
{
	return timeGetTime();
}

void _Timer::StartCounter(int & prevTime)
{
	prevTime = timeGetTime();
}

int _Timer::GetCounter(int prevTime)
{
	return timeGetTime() - prevTime;
}

double _Timer::GetTimePrecise(bool ms)
{
	LARGE_INTEGER time;
	QueryPerformanceCounter(&time);

	if(ms)	return time.QuadPart / (PerformanceCounterFreq * 1000);
	else	return time.QuadPart / PerformanceCounterFreq;
}

void _Timer::StartCounterPrecise(double & prevTime, bool ms)
{
	prevTime = GetTimePrecise(ms);
}

double _Timer::GetCounterPrecise(double prevTime, bool ms)
{
	return GetTimePrecise(ms) - prevTime;
}

bool _Timer::GetDelay(const int delay, int & prevTime)
{
	if(prevTime == 0) prevTime = timeGetTime();	// Reset/initialise prevTime
	int currTime = timeGetTime();				// Initialise currTime

	if(currTime - prevTime > delay)
	{
		prevTime = 0;
		return true;
	}

	return false;
}

bool _Timer::GetDelayPrecise(const double delay, double & prevTime, bool ms)
{
	if(prevTime == 0) prevTime = GetTimePrecise(ms);// Reset/initialise prevTime
	double currTime = GetTimePrecise(ms);			// Initialise currTime

	if(currTime - prevTime > delay)
	{
		prevTime = 0;
		return true;
	}

	return false;
}